{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "from faker import Faker\n",
    "import json\n",
    "import requests\n",
    "import random\n",
    "import time\n",
    "from concurrent.futures import ThreadPoolExecutor, as_completed\n",
    "from tqdm import tqdm\n",
    "fake = Faker('zh_CN')"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "api_url = \"http://localhost:7000\"\n",
    "def path_join(*args, base_url = api_url):\n",
    "    return base_url + \"/\".join(args)\n",
    "def to_json(data, format = False):\n",
    "    args = {\n",
    "        \"ensure_ascii\": False\n",
    "    }\n",
    "    if format: args[\"indent\"] = 4\n",
    "    return json.dumps(data, **args)"
   ],
   "id": "3420a84e14fdbef2",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "def create_session(username = 'caixypromise', password = 'as123456789'):\n",
    "    url = path_join(\"/api/user/login\")\n",
    "    data = {\n",
    "        \"userAccount\": username,\n",
    "        \"userPassword\": password\n",
    "    }\n",
    "    session = requests.session()\n",
    "    succeed = session.post(url, json=data).json()\n",
    "    if succeed.get('code') is None or succeed.get('code') != 0:\n",
    "        print(f\"登录失败: {succeed}\")\n",
    "    print(f\"登录成功: {to_json(succeed, True)}\")\n",
    "    return session\n",
    "session = create_session()"
   ],
   "id": "3bc753d3a7405d02",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "def get(url, params=None):\n",
    "    response = session.get(path_join(url), params=params, timeout=5)\n",
    "    return response.json()"
   ],
   "id": "f8198f526dabe6ea",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "def post(url, data=None):\n",
    "    response = session.post(path_join(url), json=data, timeout=5)\n",
    "    return response.json()"
   ],
   "id": "564f0c84b8a9c34d",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "def put(url, data=None):\n",
    "    response = session.put(path_join(url), json=data, timeout=5)\n",
    "    return response.json()"
   ],
   "id": "e8d7d5c71d71186a",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "def delete(url, data=None):\n",
    "    response = session.delete(path_join(url), json=data, timeout=5)\n",
    "    return response.json()"
   ],
   "id": "6860daa6d03609a5",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "subject_names = [\n",
    "    \"数学\", \"语文\", \"英语\", \"物理\", \"化学\", \"生物\", \"历史\", \"地理\", \"政治\", \"计算机\",\n",
    "    \"美术\", \"音乐\", \"体育\", \"心理学\", \"经济学\", \"法学\", \"哲学\", \"社会学\", \"统计学\", \"医学\",\n",
    "    \"环境科学\", \"天文学\", \"人工智能\", \"大数据\", \"数据结构\", \"操作系统\", \"网络安全\", \"软件工程\",\n",
    "    \"微积分\", \"线性代数\", \"概率论\", \"数理逻辑\", \"编译原理\", \"生物化学\", \"电子工程\", \"自动控制\",\n",
    "    \"机器人学\", \"农业科学\", \"食品安全\", \"旅游管理\", \"市场营销\", \"国际贸易\", \"广告学\", \"新闻学\",\n",
    "    \"传播学\", \"艺术设计\", \"摄影\", \"电影制作\", \"表演\", \"舞蹈\", \"体育健康\", \"运动科学\",\n",
    "    \"营养学\", \"护理学\", \"药学\", \"生物工程\", \"遗传学\", \"分子生物学\", \"生态学\", \"气象学\",\n",
    "    \"地质学\", \"测绘学\", \"水利工程\", \"土木工程\", \"交通工程\", \"航天工程\", \"新能源科学\",\n",
    "    \"光学\", \"核物理\", \"无线通信\", \"高等数学\", \"初等数学\", \"代数\", \"几何\", \"拓扑学\",\n",
    "    \"逻辑学\", \"伦理学\", \"心理咨询\", \"企业管理\", \"财务管理\", \"会计学\", \"税务学\",\n",
    "    \"人力资源管理\", \"供应链管理\", \"物联网\", \"虚拟现实\", \"增强现实\", \"区块链\", \"智能制造\",\n",
    "    \"精密仪器\", \"化工\", \"生物医学工程\", \"网络编程\", \"前端开发\", \"后端开发\", \"云计算\",\n",
    "    \"数据库管理\", \"移动开发\", \"自动化控制\", \"金融学\", \"保险学\"\n",
    "]\n",
    "# 添加科目\n",
    "for name in subject_names:\n",
    "    grade_max = 100\n",
    "    grade_min = 0\n",
    "    grade_excellent = random.randint(85, grade_max)\n",
    "    grade_fail = random.randint(grade_min, 60)\n",
    "    credit_hours = random.randint(30, 100)\n",
    "    course_type = 1 if random.random() < 0.5 else 0\n",
    "    grade_credit = float(random.randint(1, 12))\n",
    "    payload = {\n",
    "        \"name\": name,\n",
    "        \"gradeMax\": grade_max,\n",
    "        \"gradeMin\": grade_min,\n",
    "        \"gradeExcellent\": grade_excellent,\n",
    "        \"gradeFail\": grade_fail,\n",
    "        \"creditHours\": credit_hours,\n",
    "        \"courseType\": course_type,\n",
    "        \"gradeCredit\": grade_credit\n",
    "    }\n",
    "    response = post('/api/subject/add', data=payload)\n",
    "    print(response)"
   ],
   "id": "d73b49e1f1b4731c",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "def get_department_data():\n",
    "    \"\"\"请求学院、专业、班级数据\"\"\"\n",
    "    try:\n",
    "        response = post('/api/classes/get/classes', data={})\n",
    "        return response\n",
    "    except Exception as e:\n",
    "        print(\"请求学院、专业、班级数据失败：\", e)\n",
    "        return None\n",
    "\n",
    "def add_student(stuName, stuSex, stuDeptId, stuMajorId, stuClassId, stuId):\n",
    "    \"\"\"发送添加学生的请求\"\"\"\n",
    "    payload = {\n",
    "        \"stuName\": stuName,\n",
    "        \"stuSex\": stuSex,\n",
    "        \"stuDeptId\": stuDeptId,\n",
    "        \"stuMajorId\": stuMajorId,\n",
    "        \"stuClassId\": stuClassId,\n",
    "        \"stuId\": stuId\n",
    "    }\n",
    "    try:\n",
    "        response = post('/api/student/add', data=payload)\n",
    "        if response.get('code') == 0:\n",
    "            return None\n",
    "        else:\n",
    "            return f\"学生 {stuName} 添加失败，状态码：{response.get('code')}，响应：{response.get('message')}\"\n",
    "    except Exception as e:\n",
    "        return f\"学生 {stuName} 添加失败，异常：{str(e)}\"\n",
    "    \n",
    "def mock_student_info():\n",
    "    # 获取学院、专业、班级数据\n",
    "    dept_data = get_department_data()\n",
    "    if not dept_data or dept_data.get(\"code\") != 0:\n",
    "        print(\"获取学院、专业、班级数据失败，退出程序\")\n",
    "        return\n",
    "\n",
    "    # 提取每个班级的相关信息：学院id、专业id、班级id\n",
    "    class_info_list = []\n",
    "    for college in dept_data[\"data\"]:\n",
    "        dept_id = int(college[\"value\"])\n",
    "        for major in college.get(\"children\", []):\n",
    "            major_id = int(major[\"value\"])\n",
    "            for clazz in major.get(\"children\", []):\n",
    "                class_id = int(clazz[\"value\"])\n",
    "                class_info_list.append((dept_id, major_id, class_id, clazz[\"label\"]))\n",
    "\n",
    "    total_students = len(class_info_list) * 50\n",
    "    print(f\"将为每个班级生成 50 个学生，总共 {total_students} 个学生记录\")\n",
    "\n",
    "    failures = []  # 用于记录请求失败的信息\n",
    "    futures = []\n",
    "    max_workers = 10\n",
    "\n",
    "    with ThreadPoolExecutor(max_workers=max_workers) as executor:\n",
    "        # 为每个班级生成 50 个学生的添加请求任务\n",
    "        for dept_id, major_id, class_id, class_label in class_info_list:\n",
    "            for _ in range(50):\n",
    "                stuName = fake.name()             # 生成中文姓名\n",
    "                stuSex = random.choice([1, 2])      # 随机性别（1 或 2）\n",
    "                stuId = \"S\" + str(random.randint(10000000, 99999999))  # 生成学号\n",
    "                futures.append(\n",
    "                    executor.submit(add_student, stuName, stuSex, dept_id, major_id, class_id, stuId)\n",
    "                )\n",
    "\n",
    "        # 使用 tqdm 监控任务进度\n",
    "        for future in tqdm(as_completed(futures), total=len(futures), desc=\"添加学生进度\"):\n",
    "            result = future.result()\n",
    "            # 失败的请求记录下来\n",
    "            if result:\n",
    "                failures.append(result)\n",
    "                print(result)\n",
    "\n",
    "    print(\"学生添加完成！\")\n",
    "    if failures:\n",
    "        print(\"以下请求失败：\")\n",
    "        for failure in failures:\n",
    "            print(failure)\n",
    "mock_student_info()"
   ],
   "id": "18f136115fff8d4a",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "def add_teacher(teacherId, teacherName, teacherSex, teacherDeptId, teacherMajorId):\n",
    "    \"\"\"发送添加教师的请求\"\"\"\n",
    "    payload = {\n",
    "        \"teacherId\": teacherId,\n",
    "        \"teacherName\": teacherName,\n",
    "        \"teacherSex\": teacherSex,\n",
    "        \"teacherDeptId\": teacherDeptId,\n",
    "        \"teacherMajorId\": teacherMajorId\n",
    "    }\n",
    "    try:\n",
    "        response = post('/api/teacher/add', data=payload)\n",
    "        if response.get(\"code\") == 0:\n",
    "            return None  # 成功则返回 None\n",
    "        else:\n",
    "            return f\"教师 {teacherName}（工号: {teacherId}） 添加失败，状态码：{response.get('code')}，错误信息：{response.get('message')}\"\n",
    "    except Exception as e:\n",
    "        return f\"教师 {teacherName}（工号: {teacherId}） 添加失败，异常：{str(e)}\"\n",
    "    \n",
    "def mock_teacher_info():\n",
    "    # 获取学院、专业、班级数据\n",
    "    dept_data = get_department_data()\n",
    "    if not dept_data or dept_data.get(\"code\") != 0:\n",
    "        print(\"获取学院、专业、班级数据失败，退出程序\")\n",
    "        return\n",
    "\n",
    "    # 提取每个专业的相关信息：学院id、专业id\n",
    "    major_info_list = []\n",
    "    for college in dept_data[\"data\"]:\n",
    "        dept_id = int(college[\"value\"])\n",
    "        for major in college.get(\"children\", []):\n",
    "            major_id = int(major[\"value\"])\n",
    "            major_info_list.append((dept_id, major_id, major[\"label\"]))\n",
    "    total_teachers = len(major_info_list) * 20\n",
    "    print(f\"将为每个专业生成 20 名教师，总共 {total_teachers} 名教师记录\")\n",
    "\n",
    "    failures = []  # 用于记录请求失败的信息\n",
    "    futures = []\n",
    "    max_workers = 10\n",
    "\n",
    "    with ThreadPoolExecutor(max_workers=max_workers) as executor:\n",
    "        # 为每个专业生成 20 名教师的添加请求任务\n",
    "        for dept_id, major_id, major_label in major_info_list:\n",
    "            for _ in range(20):\n",
    "                teacherName = fake.name()             # 生成中文姓名\n",
    "                teacherSex = random.choice([1, 2])    # 随机性别（1 男，2 女）\n",
    "                teacherId = \"T\" + str(random.randint(10000000, 99999999))  # 生成教师工号\n",
    "                futures.append(\n",
    "                    executor.submit(add_teacher, teacherId, teacherName, teacherSex, dept_id, major_id)\n",
    "                )\n",
    "\n",
    "        # 使用 tqdm 监控任务进度\n",
    "        for future in tqdm(as_completed(futures), total=len(futures), desc=\"添加教师进度\"):\n",
    "            result = future.result()\n",
    "            # 失败的请求记录下来\n",
    "            if result:\n",
    "                failures.append(result)\n",
    "\n",
    "    print(\"教师添加完成！\")\n",
    "    if failures:\n",
    "        print(\"以下请求失败：\")\n",
    "        for failure in failures:\n",
    "            print(failure)\n",
    "mock_teacher_info()"
   ],
   "id": "d4d6bfc9a3e2fdbe",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": "",
   "id": "27744f9a93dfc8cc",
   "outputs": [],
   "execution_count": null
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
